const  { readFileSync }  = require('fs')
const  { resolve } = require('path')
const INNER_MARK = '<!-- comment -->'

class MdToHtml {
	constructor({template,filename}){
		if (!template){
			throw new Error('The config for "template" must be configured')
		}
		this.template = template
		this.filename = filename ? filename : 'md.html'
	}
	apply(compiler){
		compiler.hooks.emit.tap('md-to-html-plugin',(compilation)=>{
			const _assets = compilation.assets
			const _mdContent = readFileSync(this.template,'utf8')
			const _templateHTML = readFileSync(resolve(__dirname,'test.html'),'utf8')
			const _htmlStr = compilerHTML(_mdContent)					
			const _finalHTML = _templateHTML.replace(INNER_MARK,_htmlStr)
			
							
			_assets[this.filename] = {
				source(){
					return _finalHTML
				},
				size(){
					return _finalHTML.size
				}
			}		
			
		})
	}
}
/**
 * [
  '# 当兵来自哪？',
   '- 来自农村；',
   '- 来自乡镇；',
   '- 来自县城；',
   '- 来自城市；',
   '## 当官来自哪？',
   '1，来自他方；',
   '2，来自地方；',
   '3，来自何方；',
   '4，来自哪方；'
 * 
 * */ 

function compilerHTML(str){
	let reg_mark =  /[(\r\n)]/g            
	   
	
	const _mdContentArr = str.trim().split(reg_mark).filter(item=>item!=='')	
	const _htmlAst = createTree(_mdContentArr)
	const domStr = htmlFromAst(_htmlAst)
	
	
	return domStr
}

function createTree(arr){
	let _objTree = {},
		reg_h1Mark = /^(#+)/,
		reg_ulMark = /^(-+)/,
		reg_olMark = /^(\d+)\s*,/,
		ulItems = [],
		olItems = []
	arr.forEach(item=>{
		let h = item.match(reg_h1Mark),
			ul = item.match(reg_ulMark),
			ol = item.match(reg_olMark)
			
		item=item.trim()	
		
		if (h && h[0] ){
			let len = h[0].length
				_objTree[`h${len}-`+Math.ceil(Math.random()*10000)] = {
					type: 'single',
					tags: [`<h${len}>`+ item.slice(len) +`</h${len}>`]
				}				
		}	
		
		if (ul && ul[0]){			
			let contentLi='<li>' + ul['input'].slice(1) + '</li>'
			ulItems.push(contentLi)
			
			_objTree['ul'] = ({
				type: 'wrap',
				tags: ulItems
			}) 			
		}
		
		if (ol && ol[0]){			
			let len = ol[0].length
			let contentLi='<li>' + ol['input'].slice(len) + '</li>'
			olItems.push(contentLi)			
			_objTree['ol'] = ({
				type: 'wrap',
				tags: olItems
			}) 			
		}		
	})
	
	return _objTree
	
}

/**
 * {
  'h1-1583': { type: 'single', tags: [ '<h1> 当兵来自哪？</h1>' ] },
  ul: {
    type: 'wrap',
    tags: [
      '<li> 来自农村；</li>',
      '<li> 来自乡镇；</li>',
      '<li> 来自县城；</li>',
      '<li> 来自城市；</li>'
    ]
  },
  'h2-4002': { type: 'single', tags: [ '<h2> 当官来自哪？</h2>' ] },
  ol: {
    type: 'wrap',
    tags: [
      '<li> 来自他方；</li>',
      '<li> 来自地方；</li>',
      '<li> 来自何方；</li>',
      '<li> 来自哪方；</li>',
      '<li> 来自无方；</li>'
    ]
  }
}
 * */ 


function htmlFromAst(obj){	
	let _htmlStr=''
	
	for (key in obj){	
		
		if (obj[key]['type'] === 'single'){
			_htmlStr += obj[key]['tags'][0] 
		}
		
		if (obj[key]['type'] === 'wrap' && /^ul/.test(key)){			
			let tagsArr = obj[key]['tags'], 
			    liStr='<ul>'
			    tagsStr = tagsArr.forEach(i=>{	
				liStr += i
			})
			
			_htmlStr += liStr + '</ul>'			
		}
		
		if (obj[key]['type'] === 'wrap' && /^ol/.test(key)){
			let tagsArr = obj[key]['tags'], 
			    liStr='<ol>',
			    tagsStr = tagsArr.forEach(i=>{
				liStr += i
			})
			
			_htmlStr += liStr + '</ol>'
		}
	}
	
	return _htmlStr
}
module.exports = MdToHtml

